<template>
  <el-row :gutter="18">
    <!-- 左边表格区域 -->
    <el-col :span="6">
      <el-card shadow="hover">
        <template #header>
          <div class="header-content">
            <!-- <el-input
              v-model="leftSearchKeyword"
              placeholder="搜索"
              style="width: 180px; margin-right: 10px;"
            /> -->
            <el-button type="primary" icon="Plus" @click="handleLeftAdd">新增</el-button>
          </div>
        </template>
        <el-table
          ref="leftTableRef"
          :data="leftTableData" 
          @row-click="handleLeftRowClick"
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column type="index" width="50" align="center" label="序号" />
          <el-table-column prop="name" label="区域名称" />
          <el-table-column label="操作" width="100" align="center">
            <template #default="scope">
              <el-tooltip content="修改" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleLeftUpdate(scope.row)" />
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-popconfirm title="是否确认删除该数据" @confirm="handleLeftDelete(scope.row)">
                  <template #reference>
                    <el-button link type="danger" icon="Delete" />
                  </template>
                </el-popconfirm>
              </el-tooltip>
            </template>
          </el-table-column>      
        </el-table>
      </el-card>
    </el-col>

    <!-- 右边表格区域 -->
    <el-col :span="18">
      <el-card shadow="hover">
        <template #header>
          <div class="header-content">
            <!-- <el-input
              v-model="rightSearchKeyword"
              placeholder="搜索"
              style="width: 180px; margin-right: 10px;"
            /> -->
            <el-button type="primary" icon="Plus" @click="handleRightAdd">新增</el-button>
          </div>
        </template>
        <el-table :data="rightTableData" style="width: 100%">
          <!-- 这里需根据实际数据结构添加列 -->
          <el-table-column type="index" width="60" align="center" label="序号" />
          <el-table-column label="布局" align="center" width="90">
            <template #default="scope">
              <el-button type="primary" plain @click="handleCheck(scope.row)" :disabled="!scope.row.ossId">布局</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="空间名称" />
          <el-table-column label="文件名" align="center" prop="fileName" />
          <el-table-column label="原名" align="center" prop="originalName" />
          <el-table-column label="图片" align="center" prop="url">
          <template #default="scope">
            <ImagePreview
              :width="100"
              :height="100"
              :src="scope.row.url"
              :preview-src-list="[scope.row.url]"
            />
          </template>
        </el-table-column>
          <el-table-column label="操作" width="180" align="center">
            <template #default="scope">
              <el-tooltip content="修改" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleRightUpdate(scope.row)" />
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-popconfirm title="是否确认删除该数据" @confirm="handleRightDelete(scope.row)">
                  <template #reference>
                    <el-button link type="danger" icon="Delete" />
                  </template>
                </el-popconfirm>
              </el-tooltip>
              <el-tooltip content="添加设备" placement="top">
                <el-button link type="primary" icon="ZoomIn" @click="handleAddDevices(scope.row)" />
              </el-tooltip>
              <el-tooltip content="查看空间设备" placement="top">
                <el-button link type="info" icon="cpu" @click="handleToDevices(scope.row.id)" />
              </el-tooltip>
            </template>
          </el-table-column>      
        </el-table>
      </el-card>
    </el-col>
  </el-row>
  <!-- 左边新增区域弹窗 -->
  <el-dialog
    :title="left_dialog.title"
    v-model="left_dialog.visible"
    width="500px"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
  >
    <el-form :model="leftForm" :rules="leftRules" ref="leftFormRef" label-width="80px">
      <el-form-item label="区域名称" prop="name">
        <el-input v-model="leftForm.name" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="left_cancel">取消</el-button>
        <el-button type="primary" @click="handleLeftConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 右边新增空间弹窗 -->
  <el-dialog
    :title="right_dialog.title"
    v-model="right_dialog.visible"
    width="500px"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
  >
    <el-form :model="rightForm" :rules="rightRules" ref="rightFormRef" label-width="80px">
      <el-form-item label="区域 ID" v-if="false">
        <el-input v-model="rightForm.homeId" disabled />
      </el-form-item>
      <el-form-item label="空间名称" prop="name">
        <el-input v-model="rightForm.name" />
      </el-form-item>
      <el-form-item label="图片">
        <imageUpload v-model="rightForm.ossId" limit="1" fileSize="20" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="right_cancel">取消</el-button>
        <el-button type="primary" @click="handleRightConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 绑定设备 -->
  <el-dialog
    title="添加设备"
    v-model="dialogDevice.visible"
    width="900px"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
    @close="cancel"
  >
    <el-form ref="queryFormRef" :model="query" :inline="true" label-width="55px">
      <el-form-item label="产品" prop="productKey">
        <el-select v-model="query.productKey" placeholder="请选择产品" clearable>
          <el-option v-for="item in productOptions" :key="item.productKey" :label="item.name" :value="item.productKey" />
        </el-select>
      </el-form-item>
      <el-form-item label="关键字" prop="keyword">
        <el-input v-model="query.keyword" placeholder="请输入关键字" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQueryDevice">搜索</el-button>
        <el-button icon="Refresh" @click="resetQueryDevice">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="deviceData"
      bordered
    >
      <el-table-column label="序号" type="index" align="center" width="50" :index="indexMethod" />
      <el-table-column label="设备自定义名称" prop="deviceCustomName">
        <template #default="scope">
          {{ scope.row.deviceCustomName || '未定义' }}
        </template>
      </el-table-column>
      <el-table-column label="产品" prop="productKey" width="200">
        <template #default="scope">
          {{ getProductName(scope.row.productKey) }}
        </template>
      </el-table-column>
      <el-table-column label="设备DN" prop="deviceName" />
      <el-table-column label="状态" prop="online" align="center" width="80">
        <template #default="scope">
          <el-tag v-if="scope.row.online" type="success" size="small">在线</el-tag>
          <el-tag v-else type="danger" size="small">离线</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" align="center">
        <template #default="scope">
          <el-button link type="primary" icon="Check" @click="handleSubmit(scope.row)">确认</el-button>
        </template>
      </el-table-column> 
    </el-table>
    <pagination
      :total="state.total" 
      v-model:page="state.page.pageNum" 
      v-model:limit="state.page.pageSize" 
      @pagination="getDeviceList"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { 
  getBuildingList, buildingUpdate, buildingAdd, buildingDelete,
  getSpaceList, spaceUpdate, spaceAdd, spaceDelete, spaceAddDevice
} from './api/building.api'
import { getDevicesList } from '../device/api/devices.api'
import { getProductsList, IProductsVO } from '../device/api/products.api'
import { FormInstance } from 'element-plus'
import ImagePreview from '@/components/ImagePreview/index.vue'
import { listByIds } from '@/api/system/oss'

interface LeftTableRow {
  id: string | number
  name: string
  homeId: string | number
}
interface RightTableRow {
  id: string | number
  name: string
  ossId: string | number | undefined
  url?: string
  fileName?: string 
  originalName?: string
}

const leftTableRef = ref(null)

// 当前选中行
const currentLeftRow = ref<LeftTableRow | null>(null)
const currentRightRow = ref<RightTableRow | null>(null)

// // 搜索
// const leftSearchKeyword = ref('')
// const rightSearchKeyword = ref('')

// 表格数据
const leftTableData = ref([])
const rightTableData = ref<RightTableRow[]>([])

// 新增/编辑弹窗
const left_dialog = reactive<DialogOption>({
  visible: false,
  title: '',
})
const right_dialog = reactive<DialogOption>({
  visible: false,
  title: '',
})
const dialogDevice = reactive<DialogOption>({
  visible: false
})

const leftFormRef = ref()
const rightFormRef = ref()
const leftForm = reactive({ 
  id: '',
  name: '' 
})
const rightForm = reactive({ 
  ossId: undefined,
  id: '',
  name: '',
  homeId: '' as string | number // 初始化时赋值为空字符串，但类型允许 number
})

const queryFormRef = ref<FormInstance>()

const state = reactive({
  page: {
    pageSize: 10,
    pageNum: 1,
  },
  total: 0,
  query: {
    productKey: undefined,
    group: undefined,
    online: undefined,
    keyword: undefined,
  },
  left_page: {
    pageSize: 10,
    pageNum: 1,
  },
  left_total: 0,
  left_loading: false,
  left_query: {
    name: ''
  },
  right_page: {
    pageSize: 10,
    pageNum: 1,
  },
  right_total: 0,
  right_loading: false,
  right_query: {
    name: ''
  },
  leftRules: {
    name: [{ required: true, message: '区域名称不能为空' }]
  },
  rightRules: {
    name: [{ required: true, message: '空间名称不能为空' }]
  },
})
const { query, left_query, right_query, leftRules, rightRules } = toRefs(state)

// 计算序号的方法
const currentPage = computed(() => state.page.pageNum)
const indexMethod = (index: number) => {
  return (currentPage.value - 1) * state.page.pageSize + index + 1 // 计算序号，假设pageSize是你每页的大小
}

// 左-表格行点击
const handleLeftRowClick = (row: any) => {
  currentLeftRow.value = row
  getRightData(row)
}

// 数据
const getLeftData = async () => {
  state.left_loading = true
  try {
    const res = await getBuildingList({
      // ...state.left_page,
      // ...state.left_query,
    })
    leftTableData.value = res.data
  } catch (error) {
    console.error('获取区域数据失败:', error)
  } finally {
    state.left_loading = false
  }
}
const getRightData = async (row) => {
  state.right_loading = true
  try {
    const spaceRes = await getSpaceList(row.id)
    rightTableData.value = spaceRes.data
    // state.right_total = res.data.total

    const ossIds = rightTableData.value
      .map((item) => item.ossId)
      .filter((ossId): ossId is string | number => typeof ossId === 'string' || typeof ossId === 'number');

    if (ossIds.length > 0) {
      const resList = await Promise.all(ossIds.map(ossId => listByIds(ossId)))

      const urlMap = resList.reduce((map, res) => {
        res.data.forEach((ossItem) => {
          if (ossItem.id) {
            map[ossItem.id] = {
              url: ossItem.url,
              // 添加文件名和原名到映射对象
              fileName: ossItem.fileName, 
              originalName: ossItem.originalName 
            }
          }
        })
        return map
      }, {} as Record<string | number, { url: string; fileName: string; originalName: string }>)

      rightTableData.value = rightTableData.value.map((item) => {
        const ossInfo = item.ossId !== undefined ? urlMap[item.ossId] : null
        return {
          ...item,
          url: ossInfo?.url || '',
          // 添加文件名和原名到 rightTableData
          fileName: ossInfo?.fileName || '', 
          originalName: ossInfo?.originalName || '' 
        }
      })
    }
  } catch (error) {
    console.error('获取空间数据失败:', error)
  } finally {
    state.right_loading = false
  }
}

// 新增
const handleLeftAdd = () => {
  left_dialog.visible = true
  left_dialog.title = '新增'
}
const handleRightAdd = () => {
  if (!currentLeftRow.value) {
    ElMessage.warning('请先选择一个区域')
    return
  }
  right_dialog.visible = true
  right_dialog.title = '新增'
  // 将左边选中区域的 id 赋值给 rightForm 的 homeId 字段
  rightForm.homeId = currentLeftRow.value.id
}

// 左-编辑
const handleLeftUpdate = (row: any) => {
  left_dialog.visible = true
  left_dialog.title = '编辑'
  nextTick(async () => {
    Object.assign(leftForm, row)
  })
}
const handleRightUpdate = (row: any) => {
  right_dialog.visible = true
  right_dialog.title = '编辑'
  nextTick(async () => {
    Object.assign(rightForm, row)
  })
}

// 新增/编辑-确定
const handleLeftConfirm = () => {
  leftFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      leftForm.id ? await buildingUpdate(leftForm) : await buildingAdd(leftForm)
      ElMessage.success('操作成功')
      left_cancel()
      await getLeftData()
    }
  })
}
const handleRightConfirm = () => {
  rightFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      rightForm.id ? await spaceUpdate(rightForm) : await spaceAdd(rightForm)
      ElMessage.success('操作成功')
      right_cancel()
      getRightData(currentLeftRow.value)
    }
  })
}

// 左边表格删除按钮点击事件
const handleLeftDelete = async (row: any) => {
  await buildingDelete(row.id)
  ElMessage.success('删除成功!')
  getLeftData()
}
const handleRightDelete = async (row: any) => {
  await spaceDelete(row.id)
  ElMessage.success('删除成功!')
  getRightData(currentLeftRow.value)
}

// 添加设备
const handleAddDevices = (row) => {
  dialogDevice.visible = true
  currentRightRow.value = row
  getDeviceList()
}

// 查询设备列表
const deviceData = ref<any[]>([])
const getDeviceList = () => {
  getDevicesList({
    ...state.page,
    ...state.query,
  })
  .then((res) => {
    deviceData.value = res.data.rows
    state.total = res.data.total
  })
}

const handleQueryDevice = () => {
  state.page.pageNum = 1
  getDeviceList()
}
const resetQueryDevice = () => {
  queryFormRef.value?.resetFields()
  handleQueryDevice()
}
const cancel = () => {
  dialogDevice.visible = false 
  queryFormRef.value?.resetFields()
}

// 确认添加设备
const handleSubmit= async (row) => {
  await spaceAddDevice({
    deviceId: row.id,
    spaceId: currentRightRow.value?.id
  }).then((res) => {
    if (res.code === 200) {
      ElMessage.success('添加成功')
      // cancelDevice()
      // dialogDevice.visible = false
    } else {
      ElMessage.error(res.message)
    }
  })
}

// 表单取消 重置
const left_cancel = () => {
  leftReset()
  left_dialog.visible = false
}
const right_cancel = () => {
  right_dialog.visible = false
  rightReset()
}
const leftReset = () => {
  leftForm.name = ''
  leftFormRef.value?.resetFields()
}
const rightReset = () => {
  rightForm.ossId = undefined
  rightForm.id = ''
  rightForm.name = ''
  rightFormRef.value?.resetFields()
}

// 产品字典
const productOptions = ref<IProductsVO[]>([])
// 获取产品下拉框数据
const getProductList = () => {
  getProductsList({
    pageNum: 1,
    pageSize: 99999,
  }).then((res) => {
    productOptions.value = res.data.rows || []
  })
}
getProductList()
// 获取产品名称
const getProductName = (productKey) => {
  const product = productOptions.value.find(p => p.productKey === productKey)
  return product ? product.name : ''
}

// 跳转配置
const router = useRouter()
const handleToDevices = (id) => {
  if (!id) return
  router.push(`buildingDevice/${id}`)
}

// 布局
const handleCheck = (row) => {
  if (!row.ossId) {
    ElMessage.warning('请先上传图片')
    return
  }
  router.push(`puttingDevice/${row.id}/${row.ossId}`)
}

onMounted(async () => {
  await getLeftData()
  // 等待左边表格数据加载完成后默认选中第一行
  nextTick(() => {
    if (leftTableData.value.length > 0) {
      const firstRow = leftTableData.value[0]
      currentLeftRow.value = firstRow
      handleLeftRowClick(firstRow)
      // 手动设置当前行
      if (leftTableRef.value) {
        (leftTableRef.value as any).setCurrentRow(firstRow)
      }
    } else {
      rightTableData.value = [] 
    }
  })
})
</script>

<style scoped>
.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .el-button {
    margin-bottom: 8px; 
  }
}
</style>